package com.ybg.user.business.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ybg.common.entity.Message;
import com.ybg.user.business.entity.*;
import com.ybg.user.business.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class UserService extends ServiceImpl<UserMapper, UserInfo> {
    private String salt(){
        return UUID.randomUUID().toString()
                .replaceAll("-", "").substring(0, 8);
    }

    private String encryptPass(String srcPass,String salt){
        return DigestUtils.md5Hex(String.format("%s%s%s", salt, srcPass,salt));
    }

    public Message userActivate(UserInfo userInfo){
        String salt = salt();
        String newPass = encryptPass(userInfo.getUserPass(),salt);
        userInfo.setUserStatus(1);
        userInfo.setSalt(salt);
        userInfo.setUserPass(newPass);
        try{
            return super.updateById(userInfo) ? Message.succeed("账号激活成功") : Message.fail("账号激活失败");
        }catch (Exception e){
            return Message.error(e);
        }
    }

    /**
     * Wrapper :
     *  eq: equals                  ==
     *  ne: notEquals               <>
     *  gt: greatThan               >
     *  ge: greatThan or equals     >=
     *  lt: lessThan                <
     *  le: lessThan or equals      <=
     *  in
     *  notIn
     *  like
     *  likeLeft
     *  likeRight
     *  notLike
     *  isNull
     *  isNotNull
     * @param userInfo
     * @return
     */
    public Message userLogin(InputUser userInfo){
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserName, userInfo.getUserName());
        wrapper.le(UserInfo::getUserStatus,1);
        try{
            UserInfo userSrc = super.getOne(wrapper);
            if(null != userSrc){
                String salt = userSrc.getSalt();
                String inputPass = encryptPass(userInfo.getUserPass(),salt);
                if(userSrc.getUserPass().equals(inputPass)){
                    //return Message.succeed(userSrc.getUserId());
                    Map<String,Object> data = new HashMap<>(2);
                    data.put("info",super.baseMapper.loginEmployee(userSrc.getUserId()));
                    data.put("menus",super.baseMapper.loginMenus(userSrc.getUserId()));
                    return Message.succeed(data);
                }
            }
            return Message.fail("账号或密码错误");
        }catch(Exception e){
            return Message.error(e);
        }
    }

    public Message userCancel(int userId){
        return  userStatusModify(userId, 2);
    }

    public Message getLoginEmployee(int userId){
        try{
            return Message.succeed(super.getBaseMapper().loginEmployee(userId));
        }catch (Exception e){
            return Message.error(e);
        }
    }

    public Message getLoginWorker(int userId){
        try{
            return Message.succeed(super.getBaseMapper().loginWorker(userId));
        }catch (Exception e){
            return Message.error(e);
        }
    }

    public Message getEmployeeById(int employeeId){
        try{
            LoginEmployee emp = super.baseMapper.getEmployeeById(employeeId);
            return null==emp ? Message.fail(String.format("编号为 %d 的员工不存在",employeeId)) : Message.succeed(emp);
        }catch (Exception e){
            log.error("根据员工编号查询员工信息异常",e);
            return Message.error(e);
        }
    }

    public Message adminUserAdd(String userName){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserName,userInfo.getUserName());
        try{
            if (super.count(wrapper)==1) {
                return Message.repeat("账号[ "+userInfo.getUserName()+" ]已存在");
            }else{
                String salt=salt();
                String newPass=encryptPass("111111",salt);
                userInfo.setSalt(salt);
                userInfo.setUserPass(newPass);
                return super.save(userInfo) ?
                        Message.succeed("新增用户[ "+userInfo.getUserName()+" ]成功") :
                        Message.fail("新增用户[ "+userInfo.getUserName()+" ]失败");
            }
        }catch(Exception e){
            log.error("管理员重置账号密码异常",e);
            return Message.error(e);
        }
    }

    private Message userStatusModify(int userId, int userStatus){
        String operation = userStatus==1 ? "解禁" : userStatus==2 ? "注销" : "禁用";
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setUserStatus(userStatus);
        try{
            return super.updateById(userInfo) ?
                    Message.succeed("账号"+operation+"成功") :
                    Message.fail("账号"+operation+"失败");
        }catch (Exception e){
            log.error("账号"+operation+"异常",e);
            return Message.error(e);
        }
    }

    public Message adminUserDisable(int userId){
        return userStatusModify(userId, 3);
    }

    public Message adminUserEnable(int userId){
        return userStatusModify(userId, 0);
    }

    public Message adminUserResetPass(int userId){
        UserInfo info = new UserInfo();
        info.setUserId(userId);
        String salt = salt();
        info.setSalt(salt);
        info.setUserPass(encryptPass("111111",salt));
        info.setUserStatus(0);
        try{
            return super.updateById(info) ?
                    Message.succeed("重置密码成功") :
                    Message.fail("重置密码失败");
        }catch (Exception e){
            log.error("管理员分配账号异常",e);
            return Message.error(e);
        }
    }

    public Message adminBindUserEmployee(int userId, int employeeId){
        try{
            if(super.baseMapper.userBoundEmployee(userId,employeeId)){
                return Message.repeat("该用户已绑定该员工");
            }
            return super.baseMapper.bindUserEmployee(userId,employeeId)>0 ?
                    Message.succeed("用户绑定员工成功") :
                    Message.fail("用户绑定员工失败");
        }catch (Exception e){
            log.error("用户绑定员工异常",e);
            return Message.error(e);
        }
    }
    /*public Message adminBindUserRole(int userId, int roleId){
        try{
            if(super.baseMapper.userBoundRole(userId,roleId)){
                return Message.repeat("该用户已绑定该角色");
            }
            return super.baseMapper.bindUserRole(userId,roleId)>0 ?
                    Message.succeed("用户绑定角色成功") :
                    Message.fail("用户绑定角色失败");
        }catch (Exception e){
            log.error("用户绑定角色异常",e);
            return Message.error(e);
        }
    }*/
    public Message adminBindUserRoles(UserRole userRole){
        // 查询已绑角色
        final List<Integer> boundRoles = super.baseMapper.userBoundRole(userRole.getUserId());

        userRole.getRoleIds().removeAll(boundRoles);
        if(userRole.getRoleIds().isEmpty()){
            return Message.fail("无效操作, 所传角色皆已绑定");
        }
        try{
            return super.baseMapper.bindUserRole(userRole) == userRole.getRoleIds().size() ?
                    Message.succeed("绑定角色成功") : Message.fail("绑定角色成功");
        }catch (Exception e){
            log.error("绑定角色异常",e);
            return Message.error(e);
        }
    }

    public Message roleUserCurr(int userId){
        try {
            final List<IdValue> list = super.baseMapper.roleUserCurr(userId);
            return list.isEmpty() ? Message.error(new RuntimeException("数据库暂无该用户异常")) :
                    Message.succeed(list);
        }catch (Exception e){
            log.error("数据用户编号查看当前角色关系异常");
            return Message.succeed(e);
        }
    }
}
